<?php

namespace app\common\model\product;

use app\common\model\goods\Category;
use think\Model;
use traits\model\SoftDelete;

class Product extends Model
{

    use SoftDelete;



    // 表名
    protected $name = 'product';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text',
        'region_text',
        'min_price',
        'image_str',
        'images_array',
    ];
    public function getImageStrAttr($v, $d)
    {
        return $d['image'] ? cdnurl($d['image'], true) : '';
    }
    public function getImagesArrayAttr($v, $d)
    {
        if ($d['images']) {
            $array = explode(',', $d['images']);
            foreach ($array as &$value) {
                $value = $value ? cdnurl($value, true) : '';
            }
            return $array;
        }
        return [];
    }

    public function getMinPriceAttr($v, $d)
    {
        return Spec::where('goods_id', $d['id'])->min('price');
    }

    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }

    public function getRegionList()
    {
        return ['1' => __('Region 1'), '2' => __('Region 2')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getRegionTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['region']) ? $data['region'] : '');
        $list = $this->getRegionList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function spec()
    {
        return $this->hasMany(Spec::class, 'goods_id', 'id');
    }



    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
